import React, { useRef, useState } from 'react'
import {
  View,
  Image,
  StyleSheet,
  TouchableOpacity,
  TouchableHighlight,
  TouchableWithoutFeedback,
  Animated,
  Modal,
  Easing,
  Alert,
  Dimensions,
} from 'react-native'
import { Separator } from '../Partition'
import { ThemedText } from '../ThemedText'
import { ExternalLink } from '../ExternalLink'
import { router } from 'expo-router'

type Props = {
  title: string
  version: string
  type?: string
  author: { url: string; name: string }
  bot?: string
  icon?: string
}

const defaultIcon = require('@/assets/images/OIP.png')

export default function BotCard({ title, version, type, author, bot, icon }: Props) {
  const rotateValue = useRef(new Animated.Value(0)).current
  const scaleAnim = useRef(new Animated.Value(1)).current
  const [modalVisible, setModalVisible] = useState(false)
  const [pressPosition, setPressPosition] = useState({ x: 0, y: 0 })

  const rotate = rotateValue.interpolate({
    inputRange: [0, 0.5, 1],
    outputRange: ['0deg', '280deg', '360deg'],
  })

  // 点击
  const handleClick = () => {
    let { url, name } = author
    // 使用路由跳转
    router.push({
      pathname: 'Detail/DetailScreen',
      params: {
        title,
        version,
        type,
        bot,
        icon,
        url,
        name,
      },
    })
  }

  // 按下
  const handlePressIn = () => {
    Animated.timing(scaleAnim, {
      toValue: 0.95,
      duration: 400,
      easing: Easing.back(3),
      useNativeDriver: true,
    }).start()
  }

  // 松开
  const handlePressOut = () => {
    Animated.timing(scaleAnim, {
      toValue: 1,
      duration: 100,
      easing: Easing.back(2),
      useNativeDriver: true,
    }).start()
    Animated.timing(rotateValue, {
      toValue: 0,
      duration: 500,
      useNativeDriver: true,
    }).start()
  }

  // 长按
  const handleLongPress = (event: any) => {
    const { width, height } = Dimensions.get('window')
    let { pageX: x, pageY: y } = event.nativeEvent

    // Adjust x and y to ensure the modal doesn't go out of bounds
    if (x > width - 150) x = width - 210
    if (y > height - 150) y = height - 210

    setPressPosition({ x, y })
    setModalVisible(true)
    Animated.timing(rotateValue, {
      toValue: 1,
      duration: 500,
      useNativeDriver: true,
    }).start()
  }

  return (
    <>
      <TouchableOpacity
        onPressIn={handlePressIn}
        onPressOut={handlePressOut}
        onLongPress={handleLongPress}
        onPress={handleClick}
        activeOpacity={1}
        delayLongPress={200}
      >
        <Animated.View style={[styles.card, { transform: [{ scale: scaleAnim }, { rotate }] }]}>
          <Image
            source={icon ? { uri: icon } : defaultIcon}
            style={styles.image}
          />
          <View style={{ width: '80%' }}>
            <ThemedText
              type="menutitle"
              style={{ fontSize: 20 }}
            >
              {title}
            </ThemedText>
            <Separator />
            <ThemedText>插件版本: {version}</ThemedText>
            <ThemedText>插件类型: {type}</ThemedText>
            <ThemedText>
              插件作者:
              <ExternalLink href={author?.url ?? ''}>{author?.name}</ExternalLink>
            </ThemedText>
            <ThemedText style={styles.text}>通知机器人: {bot ? bot : '未知'}</ThemedText>
          </View>
        </Animated.View>
      </TouchableOpacity>
      <Modal
        transparent={true}
        visible={modalVisible}
        onRequestClose={() => setModalVisible(false)}
      >
        <TouchableWithoutFeedback onPress={() => setModalVisible(false)}>
          <View style={styles.modalOverlay}>
            <View style={[styles.modalContent, { top: pressPosition.y, left: pressPosition.x }]}>
              <TouchableHighlight
                onPress={() => Alert.alert('吃了吗')}
                underlayColor="#f0f0f0"
              >
                <ThemedText style={styles.modalText}>选项 1</ThemedText>
              </TouchableHighlight>
              <TouchableHighlight
                onPress={() => Alert.alert('没吃')}
                underlayColor="#f0f0f0"
              >
                <ThemedText style={styles.modalText}>选项 2</ThemedText>
              </TouchableHighlight>
              <TouchableHighlight
                onPress={() => Alert.alert('吃过了')}
                underlayColor="#f0f0f0"
              >
                <ThemedText style={styles.modalText}>选项 3</ThemedText>
              </TouchableHighlight>
            </View>
          </View>
        </TouchableWithoutFeedback>
      </Modal>
    </>
  )
}
const styles = StyleSheet.create({
  card: {
    flexDirection: 'row',
    backgroundColor: '#fff',
    width: '90%',
    borderRadius: 10,
    padding: 20,
    margin: 4,
    marginBottom: 10,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.2,
    shadowRadius: 5,
    elevation: 5,
  },
  header: {},
  image: {
    width: 50,
    height: 50,
    borderRadius: 25,
    marginRight: 10,
  },
  title: {
    fontSize: 18,
    fontWeight: 'bold',
  },
  text: {
    fontSize: 16,
    marginVertical: 2,
  },
  modalOverlay: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  modalContent: {
    position: 'absolute',
    width: 200,
    backgroundColor: 'white',
    padding: 10,
    borderRadius: 5,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.8,
    shadowRadius: 2,
    elevation: 5,
  },
  modalText: {
    fontSize: 16,
    marginVertical: 10,
  },
})
